package com.develop.BusinessGatewayService;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.develop.BeanUtils.KafkaSender;
import com.develop.protocol.AlarmDecoder;
import com.develop.protocol.AlarmEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * netty server端
 *
 * 功能：与通信网关通信使用
 **/

@Component
public class BusinessGatewayService {
	@Autowired
	private KafkaSender kafkaSender;
	private static final Logger LOG = LoggerFactory.getLogger(BusinessGatewayService.class);
	@Value("${businessGatewayService.server.readerIdleTime}")
	public int readIdelTimeOut;
	@Value("${businessGatewayService.server.logLevel}")
	public String logLevel;

	public void run(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					// 保持长连接
					.option(ChannelOption.SO_BACKLOG, 10).option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true).handler(new LoggingHandler(logLevel)).childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel channel) throws Exception {
							ChannelPipeline pipeline = channel.pipeline();
							// 字符串解码和编码
							pipeline.addLast(new ChannelHandler[] { new AlarmDecoder(32767, 7, 2, 0, 0, false) });
							pipeline.addLast(new ChannelHandler[] { new AlarmEncoder() });
							// 服务端心跳检测
							pipeline.addLast(new IdleStateHandler(readIdelTimeOut, 0, 0, TimeUnit.SECONDS));
							pipeline.addLast("handler", new BusinessGatewayServerHandler(kafkaSender));
						}
					});
			Channel channel = bootstrap.bind(port).sync().channel();
			LOG.info("BusinessGatewayService 已经启动，端口：" + port + ".");
			channel.closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
